<template>
  <div class="app-container org">
    <el-card style="width: 100%">
      <p class="pinformation" style="margin-top: 7px">搜索条件</p>
      <el-form label-width="100px" :model="queryParams" ref="queryRef">
        <el-row>
          <el-col :span="3">
            <el-form-item label="方案编号：" prop="projectCode">
              <el-input
                v-model="queryParams.projectCode"
                clearable
                maxlength="100"
                @keyup.enter="handeleQuery"
                placeholder="请输入方案编号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="方案名称：" prop="projectName">
              <el-input
                v-model="queryParams.projectName"
                clearable
                maxlength="100"
                @keyup.enter="handeleQuery"
                placeholder="请输入方案名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="委托单位：" prop="wtCustomName">
              <el-input
                v-model="queryParams.wtCustomName"
                clearable
                maxlength="100"
                @keyup.enter="handeleQuery"
                placeholder="请输入委托单位"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="合同编号：" prop="contractCode">
              <el-input
                v-model="queryParams.contractCode"
                clearable
                maxlength="100"
                @keyup.enter="handeleQuery"
                placeholder="请输入合同编号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="合同名称：" prop="contractName">
              <el-input
                v-model="queryParams.contractName"
                clearable
                maxlength="100"
                @keyup.enter="handeleQuery"
                placeholder="请输入合同名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="周期类型：" prop="cycleDesc">
              <el-select clearable v-model="queryParams.cycleDesc">
                <el-option
                  v-for="dict in proxy.addListNoLimit(sys_point_cycle)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3" v-if="queryParams.isReport == 1">
            <el-form-item label="报告编号：" prop="reportCode">
              <el-input
                v-model="queryParams.reportCode"
                clearable
                maxlength="100"
                @keyup.enter="handeleQuery"
                placeholder="请输入报告编号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="方案类型：" prop="contractType">
              <el-select clearable v-model="queryParams.contractType">
                <el-option
                  v-for="dict in proxy.addListNoLimit(sys_contract_type)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="计划开始时间：">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                :clearable="false"
                :editable="false"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="委托单位：" prop="wtCustomName">
              <el-input
                v-model="queryParams.wtCustomName"
                clearable
                maxlength="100"
                @keyup.enter="handeleQuery"
                placeholder="请输入委托单位"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="加急状态：" prop="degree">
              <el-select clearable v-model="queryParams.degree">
                <el-option
                  v-for="dict in proxy.addListNoLimit(sys_degree)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="padding-left: 30px">
            <el-button type="success" @click="handeleQuery">搜索</el-button>
            <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <p class="pinformation">方案列表</p>
        <p class="totalStyle">共 {{ total }} 条数据</p>
      </el-row>
      <el-table
        ref="mainTableRef"
        :data="projectList"
        @selection-change="handleSelectionChange"
        border
      >
                <el-table-column prop="reportCode" label="报告编号" align="center"  width="120" v-if="queryParams.isReport == 1"/>
        <el-table-column prop="reportCompiler" label="报告编制人" align="center"  width="100" v-if="queryParams.isReport == 1"/>
        <el-table-column prop="reportTime" label="编制时间" align="center"  width="100" v-if="queryParams.isReport == 1"/>
        <el-table-column prop="projectUserName" label="项目负责人" align="center"  width="100" />
        <el-table-column prop="projectCode" label="方案编号" align="center"   width="120"/>
        <el-table-column prop="projectName" label="方案名称" align="center" />
        <el-table-column prop="contractCode" label="合同编号" align="center"  width="120"/>
        <el-table-column prop="wtCustomName" label="委托单位" align="center" />
                <el-table-column prop="planDate" label="计划开始时间" align="center"  width="120"/>
        <el-table-column prop="requireDate" label="合同要求完成时间" align="center" width="140"/>
        <el-table-column label="方案类型" align="center" width="120">
          <template #default="scope">
            <dict-tag :options="sys_contract_type" :value="scope.row.contractType" />
          </template>
        </el-table-column>
                <el-table-column label="周期类型" align="center" width="100">
          <template #default="scope">
            <dict-tag
              :options="sys_point_cycle"
              :value="scope.row.cycleDesc.split(',')"
            />
          </template>
        </el-table-column>
                <el-table-column label="紧急类型" align="center" width="90">
          <template #default="scope">
            <dict-tag :options="sys_degree" :value="scope.row.degree" />
          </template>
        </el-table-column>
                <el-table-column prop label="操作" align="center" width="170">
          <template #default="scope">
            <el-button link type="success" @click="download(scope.row)"
              >生成报告</el-button
            >
            <el-button link type="success" @click="upload(scope.row)">上传报告</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handeleQuery"
      />
    </el-card>
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      :close-on-click-modal="false"
      v-model="open"
      title="生成报告"
      width="800"
    >
      <el-form ref="scbgRef" :model="scbgForm" :rules="scbgRules">
        <el-form-item label="报告模板：" prop="templateId">
          <el-select
            v-model="scbgForm.templateId"
            placeholder="请选择报告模板"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in templateList"
              :key="item.templateId"
              :label="item.templateName"
              :value="item.templateId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报告编号：" prop="reportCode">
          <el-input
            v-model="scbgForm.reportCode"
            clearable
            maxlength="100"
            placeholder="请输入报告编号"
          ></el-input>
        </el-form-item>
        <el-form-item label="编制日期：" prop="reportDate">
          <el-date-picker
            v-model="scbgForm.reportDate"
            placeholder="请选择报告编制日期"
            type="date"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <el-row style="margin-top: 7px">
        <p class="pinformation">历史记录</p>
        <span class="totalStyle"> 共{{ historyList.length }}条数据 </span>
      </el-row>
      <el-table :data="historyList" height="50vh" v-loading="loading">
        <el-table-column label="序号" type="index" width="70" align="center" />
        <el-table-column
          prop="reportName"
          label="检测报告"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span
              style="
                color: var(--theme-deep-color);
                text-decoration: underline;
                cursor: pointer;
              "
              @click="handleReportName(scope.row)"
              >{{ scope.row.reportName }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="createUserName"
          label="创建人"
          align="center"
          width="80"
          show-overflow-tooltip
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          width="160"
          show-overflow-tooltip
        />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleReporting">生成报告</el-button>
          <el-button type="danger" @click="open = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      :close-on-click-modal="false"
      v-model="uploadOpen"
      title="上传报告"
      width="800"
    >
      <el-form ref="uploadRef" :model="uploadForm" :rules="uploadRule">
        <fileUpload
          v-model="uploadForm.reportFile"
          :autoUpload="true"
          :fileId="uploadForm.fileId"
          :fileType="['xls','xlsx', 'doc','docx', 'pdf']"
        ></fileUpload>
        <el-form-item label="报告编号：" prop="reportCode">
          <el-input
            v-model="uploadForm.reportCode"
            clearable
            maxlength="100"
            placeholder="请输入报告编号"
          ></el-input>
        </el-form-item>
        <el-form-item label="编制日期：" prop="reportDate">
          <el-date-picker
            v-model="uploadForm.reportDate"
            placeholder="请选择报告编制日期"
            type="date"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleStartFlow">发起报告评审</el-button>
          <!-- <el-button type="primary" @click="handleSaveFile">保存</el-button> -->
          <el-button type="danger" @click="uploadOpen = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import useRouteView from "@/store/modules/routeView";
import {
  getProjectContract,
  getTemplateList,
  getFile,
  getHistoryList,
  insertReportFile,
} from "@/api/report/reportProject";
import { definitionStartByCategory } from "@/api/flowable/definition";
import { getToken } from "@/utils/auth";
import axios from "axios";
import { blobValidate } from "@/utils/ruoyi";
import { saveAs } from "file-saver";
const router = useRouter();
const route = useRoute();
const routeViewStore = useRouteView();

const baseURL = import.meta.env.VITE_APP_BASE_API;
const { proxy } = getCurrentInstance();
const {
  sys_contract_type,
  sys_degree,
  sys_project_step,
  sys_point_cycle,
} = proxy.useDict(
  "sys_contract_type",
  "sys_degree",
  "sys_project_step",
  "sys_point_cycle"
);
const projectList = ref([]);
const total = ref(0);
const projectIds = ref([]);
const dateRange = ref([]);
const scbgForm = ref({});
const uploadForm = ref({});
const templateList = ref([]);
const historyList = ref([]);
const loading = ref(false);
const open = ref(false);
const uploadOpen = ref(false);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractType: -1,
    cycleDesc: -1,
    degree: -1,
  },
});
const { queryParams, form } = toRefs(data);
const props = defineProps({
  step: {
    type: Number, //参数类型
  },
  isReport: {
    type: Number, //参数类型
  },
});
queryParams.value.isReport = props.isReport;
const scbgRules = ref({
  reportDate: [{ required: true, message: "编制日期不能为空", trigger: "blur" }],
  reportCode: [{ required: true, message: "报告编号不能为空", trigger: "blur" }],
  templateId: [{ required: true, message: "报告模板不能为空", trigger: "blur" }],
});
const uploadRule = ref({
  reportDate: [{ required: true, message: "编制日期不能为空", trigger: "blur" }],
  reportCode: [{ required: true, message: "报告编号不能为空", trigger: "blur" }],
  fileId: [{ required: true, message: "报告模板不能为空", trigger: "blur" }],
});
const emits = defineEmits(["projectId", "projectId2"]);
let fileData = {};
function handeleQuery() {
  getProjectContract(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      projectList.value = res.rows;
      total.value = res.total;
    }
  );
}

function handleSelectionChange(selection) {
  projectIds.value = selection.map((item) => {
    return item.projectId;
  });
}

function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [];
  handeleQuery();
}

function handleReporting() {
  proxy.$refs["scbgRef"].validate((valid) => {
    if (valid) {
      proxy.$modal.loading("正在生成检测报告，请稍候...");
      getFile(scbgForm.value)
        .then((res) => {
          open.value = false;
          proxy.$modal.closeLoading();
          fileData.fileId = res.data.fileId;
          fileData.fileName = res.data.fileName;
          fileData.reportId = res.data.reportId;
          let testParam = getToken() + "φpageOffice";
          POBrowser.openWindow(
            "/report/word?fileId:" +
              res.data.fileId +
              "&fileName:" +
              res.data.fileName +
              "&reportId:" +
              res.data.reportId,
            "fullscreen=yes;",
            testParam
          );
        })
        .catch((res) => {
          proxy.$modal.closeLoading();
        });
    }
  });
}

function download(row) {
  scbgForm.value = { relId: row.projectId };
  open.value = true;
  getTemplateList().then((res) => {
    templateList.value = res.data;
  });
  loading.value = true;
  getHistoryList({ relId: row.projectId }).then((res) => {
    historyList.value = res.data;
    loading.value = false;
  });
}

function upload(row) {
  uploadOpen.value = true;
  uploadForm.value = { relId: row.projectId };
}

function handleSaveFile() {
  return new Promise((resolve, reject) => {
    if (!uploadForm.value.reportFile || uploadForm.value.reportFile.length == 0) {
      proxy.$modal.msgError("请上传检测报告！");
      return;
    }
    proxy.$refs["uploadRef"].validate((valid) => {
      if (valid) {
        uploadForm.value.fileId = uploadForm.value.reportFile[0].fileId;
        uploadForm.value.reportName = uploadForm.value.reportFile[0].fileName;
        insertReportFile(uploadForm.value).then((res) => {
          resolve(res.data);
        });
      }
    });
  });
}

function handleStartFlow() {
  handleSaveFile().then((reportId) => {
    let variables = {
      reportId: reportId,
      key: reportId,
      projectId: uploadForm.value.relId,
    };
    variables.fileIds = [uploadForm.value.reportFile[0].fileId];

    definitionStartByCategory(0, variables).then((res) => {
      proxy.$modal.msgSuccess("生成报告审核流程成功");
      if (res.data) {
        if (routeViewStore.routeView1) {
          proxy.$tab.closePage(routeViewStore.routeView1);
        }
        router.push({
          path: "/flowable/task/record/index",
          query: {
            deployId: res.data.deployId,
            procInsId: res.data.procInsId,
            executionId: res.data.executionId,
            taskId: res.data.taskId,
            finished: true,
            path: "/task/todo",
          },
        });
        uploadOpen.value = false;
      } else {
        proxy.$modal.msgError("流程启动失败，未找到报告审核流程！");
      }
    });
  });
}

function tolc() {
  if ($.isEmptyObject(fileData)) {
    proxy.$modal.msgError("未找到报告数据！");
    return;
  }
  let variables = fileData;
  variables.key = variables.reportId;
  variables.projectId = scbgForm.value.relId;
  definitionStartByCategory(0, variables).then((res) => {
    proxy.$modal.msgSuccess("生成报告审核流程成功");
    if (res.data) {
      if (routeViewStore.routeView1) {
        proxy.$tab.closePage(routeViewStore.routeView1);
      }
      router.push({
        path: "/flowable/task/record/index",
        query: {
          deployId: res.data.deployId,
          procInsId: res.data.procInsId,
          executionId: res.data.executionId,
          taskId: res.data.taskId,
          finished: true,
          path: "/task/todo",
        },
      });
    } else {
      proxy.$modal.msgError("流程启动失败，未找到报告审核流程！");
    }
  });
}
function handleReportName(row) {
  open.value = false;
  fileData.fileId = row.fileList[0]?.fileId;
  fileData.fileName = row.fileList[0]?.fileName;
  fileData.reportId = row.reportId;
  let testParam = getToken() + "φpageOffice";
  POBrowser.openWindow(
    "/report/word?fileId:" +
      row.fileList[0]?.fileId +
      "&fileName:" +
      row.fileList[0]?.fileName +
      "&reportId:" +
      row.reportId,
    "fullscreen=yes;",
    testParam
  );
}
defineExpose({
  getTableHeight,
});
watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 73 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 22 }];
    }
    getTableHeight();
  }
);

watch(
  () => route,
  (newVal) => {
    if (newVal.path == "/flowable/task/record/index") {
      const { path, name, meta } = newVal;
      routeViewStore.setRouteView1({ path, name, meta });
    }
  }
);

const heightParams = ref([{ tableName: "main", bottomHeight: 22 }]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}

onMounted(() => {
  nextTick(() => {
    window.tolc = tolc;
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
});
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});
handeleQuery();
</script>

<style></style>
